package com.internship.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.internship.model.DepartmentInfo;
import com.internship.model.Paper;
import com.internship.page.Page;
import com.internship.service.Const;
import com.internship.service.DepartmentInfoService;
import com.internship.service.FileUpload;
import com.internship.service.PaperService;
import com.internship.util.StringUtil;


@Controller
@RequestMapping("paper")
public class PaperController {
	private final Logger logger = Logger.getLogger(PaperController.class);
	
	@Autowired
	private PaperService paperService;
	@Autowired
	private DepartmentInfoService 	departmentInfoService;
	public static HttpSession getSession() {
		HttpSession session = null;
		try {
			session = getRequest().getSession();
		} catch (Exception e) {
		}
		return session;
	}

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes();
		return attrs.getRequest();
	}
	private void clearSession() {
		getSession().invalidate();
	}
	
	@RequestMapping("/paper_list.do")
	public ModelAndView getPaperList() {
		return getPaperList(null,null,1);
	}
	
	private List<DepartmentInfo>  departmentInfoList = null;
	@RequestMapping("/paper_page_list.do")
	public ModelAndView getPaperList(@RequestParam String DeptCode,@RequestParam String Title,@RequestParam int pageNumber) {
		ModelAndView mv = new ModelAndView("paper");
		HttpSession session = getSession();
		try {
			if (String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("2")||String.valueOf(session.getAttribute(Const.USER_ROLE)).equals("1")) {
				Page<Paper> pageList = paperService.getPlanList(DeptCode, Title, pageNumber);
				this.departmentInfoList = departmentInfoService.getDepartmentInfoList();
				mv.addObject("currentPage", pageNumber);
				mv.addObject("DeptCode", DeptCode);
				mv.addObject("totalPage", pageList.getTotalPage());
				mv.addObject("departmentInfoList",departmentInfoList);
				mv.addObject("totalCount", pageList.getTotalCount());
				mv.addObject("paperList", pageList.getResultList());
			}else {
				Page<Paper> pageList = paperService.getPlanList(String.valueOf(session.getAttribute(Const.USER_DEPARTMENT_CODE)), Title, pageNumber);
				mv.addObject("currentPage", pageNumber);
				mv.addObject("totalPage", pageList.getTotalPage());
				mv.addObject("totalCount", pageList.getTotalCount());
				mv.addObject("paperList", pageList.getResultList());
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		mv.addObject("Title",Title);
		return mv;
	}
	/***?
	 * 上传文档
	 * @return
	 */
	
	@RequestMapping("/paper_add.do")
	public ModelAndView paperAdd() {
		ModelAndView mv = new ModelAndView("paper_add");
		this.departmentInfoList = departmentInfoService.getDepartmentInfoList();
		mv.addObject("departmentInfoList",departmentInfoList);
		return mv;
	}
	@RequestMapping("/uploadpaper.do")
	@ResponseBody
	public net.sf.json.JSONObject uploadpaper(@RequestParam("fileAdd") MultipartFile fileAdd,@RequestParam("DeptCode")String DeptCode,@RequestParam("Title")String Title ){
		net.sf.json.JSONObject json = new net.sf.json.JSONObject();
		HttpSession session = getSession();
		Paper paper = new Paper();
		paper.setTitle(Title);
		paper.setDeptCode(DeptCode);
		if (!DeptCode.equals("00")) {
			DepartmentInfo departmentInfo = departmentInfoService.getDepartmentInfoByXYDM(DeptCode);
			System.out.println(departmentInfo.getXYMC()+"=========");
			paper.setDisplayName(departmentInfo.getXYMC());
		}else {
			paper.setDisplayName("全校");
		}
		if (fileAdd.isEmpty()==false) {
			String result = FileUpload.File(fileAdd);
			paper.setAttachment(result);
		}
		paper.setTeacherNumber(String.valueOf(session.getAttribute(Const.SESSION_ACCOUNT)));
		paper.setPubTime(StringUtil.getStrDateTime());
		paper.setDownloadCount(0);
		int rel =paperService.addPaper(paper);
		json.put("result", rel>0?"success":"error");
		return json;
	}
	/**?
	 * 删除
	 * @param Id
	 * @return
	 */
		@RequestMapping("/delete.do")
		@ResponseBody
		public JSONObject delPaper(@RequestParam int id){
			JSONObject json = new JSONObject();
			int  rel= paperService.delPaper(id);
			json.put("result", rel > 0 ?"success":"error");
			 return json; 
		}
		/**?
		 * 下载文档
		 * @param id
		 * @param request
		 * @param response
		 */
		@RequestMapping("/DownloadPaper.do")
		public void DownloadPaper(@RequestParam int id,HttpServletRequest request,   HttpServletResponse response) {
				Paper p = paperService.getPaperById(id); 
				try {
					request.setCharacterEncoding("UTF-8");
					BufferedInputStream bis = null;  
			        BufferedOutputStream bos = null;  
				if (p != null) {
					String realPath = getSession().getServletContext().getRealPath("/")+ p.getAttachment();// 获取要下载的文件的绝对路径
					String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);// 获取要下载的文件名
					// 设置content-disposition响应头控制浏览器以下载的形式打开文件，中文文件名要使用URLEncoder.encode方法进行编码，否则会出现文件名乱码
					InputStream in = new FileInputStream(realPath);// 获取文件输入流
					 //获取文件的长度
			        long fileLength = new File(realPath).length();  
			        //设置文件输出类型
			        response.setContentType("application/octet-stream");  
			        response.setHeader("Content-disposition", "attachment; filename="  
			                + new String(fileName.getBytes("utf-8"), "ISO8859-1")); 
			        //设置输出长度
			        response.setHeader("Content-Length", String.valueOf(fileLength));  
			        //获取输入流
			        bis = new BufferedInputStream(new FileInputStream(realPath));  
			        //输出流
			        bos = new BufferedOutputStream(response.getOutputStream());  
			        byte[] buff = new byte[2048];  
			        int bytesRead;  
			        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
			            bos.write(buff, 0, bytesRead);  
			        }  
			        //关闭流
			        bis.close();  
			        bos.close();  
			        }
					paperService.updateDownloadCount(id);
				}catch(Exception e){
	                  e.printStackTrace();
	          }
			
		}}
